﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "生产工单";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-3">
        <div class="col-md-6">
            <h2 class="mb-0">生产工单</h2>
        </div>
        <div class="col-md-6 d-flex justify-content-end align-items-center">
            <button class="btn btn-primary me-2" onclick="window.location.href='/Home/OrderAdd'">
                <i class="fas fa-plus"></i> 新增
            </button>
            <div class="input-group" style="width: 300px;">
                <input type="text" class="form-control" id="searchInput" placeholder="请搜索" aria-label="搜索">
                <button class="btn btn-outline-secondary" type="button" id="searchBtn">
                    <i class="fas fa-search"></i>
                </button>
                <button class="btn btn-outline-secondary" type="button" id="filterBtn" data-bs-toggle="modal" data-bs-target="#filterModal">
                    <i class="fas fa-th"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Table Section -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="workOrderTable">
                    <thead class="table-light">
                        <tr>
                            <th>
                                <input type="checkbox" class="form-check-input" id="selectAll">
                            </th>
                            <th>序号</th>
                            <th>工单编号</th>
                            <th>工单名称</th>
                            <th>物品名称</th>
                            <th>状态</th>
                            <th>负责人</th>
                            <th>所在部门</th>
                            <th>计划开始时间</th>
                            <th>实际开始时间</th>
                            <th>计划结束时间</th>
                            <th>实际结束时间</th>
                            <th>计划产量</th>
                            <th>合格数量</th>
                            <th>不合格数量</th>
                            <th>合格率</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="workOrderTableBody">
                        <!-- 数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>

            <!-- Loading Spinner -->
            <div id="loadingSpinner" class="text-center py-4" style="display: none;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2 text-muted">正在加载数据...</p>
            </div>

            <!-- No Data Message -->
            <div id="noDataMessage" class="text-center py-4" style="display: none;">
                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                <p class="text-muted">暂无数据</p>
            </div>

            <!-- Pagination Section -->
            <div class="row mt-3" id="paginationSection">
                <div class="col-md-6 d-flex align-items-center">
                    <span class="text-muted" id="dataCountInfo">共 0 项数据</span>
                    <select class="form-select ms-3" id="pageSizeSelect" style="width: auto;">
                        <option value="15" selected>15条/页</option>
                        <option value="20">20条/页</option>
                        <option value="50">50条/页</option>
                        <option value="100">100条/页</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-end align-items-center">
                        <nav aria-label="分页导航">
                            <ul class="pagination mb-0 me-3" id="pagination">
                                <!-- 分页按钮将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                        <div class="input-group" style="width: 120px;">
                            <input type="number" class="form-control" id="jumpToPage" placeholder="跳至" min="1" aria-label="跳至页">
                            <span class="input-group-text">页</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查询条件模态框 -->
<div class="modal fade" id="filterModal" tabindex="-1" aria-labelledby="filterModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="filterModalLabel">查询条件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="filterOrderNumber" class="form-label">工单编号</label>
                        <input type="text" class="form-control" id="filterOrderNumber" placeholder="请输入工单编号">
                    </div>
                    <div class="col-md-6">
                        <label for="filterOrderName" class="form-label">工单名称</label>
                        <input type="text" class="form-control" id="filterOrderName" placeholder="请输入工单名称">
                    </div>
                    <div class="col-md-6">
                        <label for="filterArticleName" class="form-label">物品名称</label>
                        <input type="text" class="form-control" id="filterArticleName" placeholder="请输入物品名称">
                    </div>
                    <div class="col-md-6">
                        <label for="filterStatus" class="form-label">状态</label>
                        <select class="form-select" id="filterStatus">
                            <option value="">全部状态</option>
                            <option value="待开始">待开始</option>
                            <option value="进行中">进行中</option>
                            <option value="已完成">已完成</option>
                            <option value="已暂停">已暂停</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="filterPrincipal" class="form-label">负责人</label>
                        <input type="text" class="form-control" id="filterPrincipal" placeholder="请输入负责人">
                    </div>
                    <div class="col-md-6">
                        <label for="filterDepartment" class="form-label">所在部门</label>
                        <input type="text" class="form-control" id="filterDepartment" placeholder="请输入部门名称">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-outline-secondary" id="resetFilter">重置</button>
                <button type="button" class="btn btn-primary" id="applyFilter">查询</button>
            </div>
        </div>
    </div>
</div>

<style>
    .progress {
        background-color: #e9ecef;
    }
    
    .progress-bar {
        background-color: #007bff;
    }
    
    .badge {
        font-size: 0.75em;
    }
    
    .table th {
        border-top: none;
        font-weight: 600;
        color: #495057;
    }
    
    .table td {
        vertical-align: middle;
    }
    
    .form-check-input:checked {
        background-color: #007bff;
        border-color: #007bff;
    }
    
    .pagination .page-link {
        color: #007bff;
        border: 1px solid #dee2e6;
    }
    
    .pagination .page-item.active .page-link {
        background-color: #007bff;
        border-color: #007bff;
    }
    
    .pagination .page-link:hover {
        color: #0056b3;
        background-color: #e9ecef;
        border-color: #dee2e6;
    }
</style>

<script>
    // 全局变量
    let currentPage = 1;
    let pageSize = 15;
    let totalCount = 0;
    let totalPages = 0;
    let workOrderData = [];
    let filterConditions = {};

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadWorkOrderData();
        bindEvents();
    });

    // 绑定事件
    function bindEvents() {
        // 全选功能
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });

        // 搜索功能
        document.getElementById('searchBtn').addEventListener('click', function() {
            currentPage = 1;
            loadWorkOrderData();
        });

        // 搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                currentPage = 1;
                loadWorkOrderData();
            }
        });

        // 页面大小改变
        document.getElementById('pageSizeSelect').addEventListener('change', function() {
            pageSize = parseInt(this.value);
            currentPage = 1;
            loadWorkOrderData();
        });

        // 跳转页面
        document.getElementById('jumpToPage').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const targetPage = parseInt(this.value);
                if (targetPage >= 1 && targetPage <= totalPages) {
                    currentPage = targetPage;
                    loadWorkOrderData();
                    this.value = '';
                } else {
                    alert(`请输入1到${totalPages}之间的页码`);
                }
            }
        });

        // 查询条件相关事件
        document.getElementById('applyFilter').addEventListener('click', function() {
            applyFilterConditions();
            const modal = bootstrap.Modal.getInstance(document.getElementById('filterModal'));
            modal.hide();
        });

        document.getElementById('resetFilter').addEventListener('click', function() {
            resetFilterConditions();
        });
    }

    // 加载工单数据
    async function loadWorkOrderData() {
        try {
            showLoading();
            
            const searchKeyword = document.getElementById('searchInput').value.trim();
            const queryParams = new URLSearchParams({
                PageIndex: currentPage.toString(),
                PageSize: pageSize.toString(),
                _ts: Date.now().toString()
            });

            if (searchKeyword) {
                queryParams.append('keyword', searchKeyword);
            }

            // 添加查询条件
            Object.keys(filterConditions).forEach(key => {
                if (filterConditions[key]) {
                    queryParams.append(key, filterConditions[key]);
                }
            });

            const url = `http://localhost:5299/api/WorkOrder/GetWorkOrderOutput?${queryParams.toString()}`;
            console.log('加载工单数据 URL:', url);

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('工单数据响应:', result);

            if (result.pageData && Array.isArray(result.pageData)) {
                workOrderData = result.pageData;
                totalCount = result.totalCount || 0;
                totalPages = Math.ceil(totalCount / pageSize);
                renderWorkOrderTable();
                renderPagination();
                updateDataCountInfo();
            } else {
                throw new Error('数据格式不正确');
            }
        } catch (error) {
            console.error('加载工单数据失败:', error);
            showError('加载数据失败: ' + error.message);
        } finally {
            hideLoading();
        }
    }

    // 渲染工单表格
    function renderWorkOrderTable() {
        const tbody = document.getElementById('workOrderTableBody');
        tbody.innerHTML = '';

        if (workOrderData.length === 0) {
            showNoData();
            return;
        }

        hideNoData();

        workOrderData.forEach((item, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="checkbox" class="form-check-input"></td>
                <td>${(currentPage - 1) * pageSize + index + 1}</td>
                <td>${item.orderNumber || ''}</td>
                <td>${item.orderName || ''}</td>
                <td>${item.articleName || ''}</td>
                <td><span class="badge ${getStatusBadgeClass(item.status)}">${item.status || '未知'}</span></td>
                <td>${item.principal || ''}</td>
                <td>${item.departmentName || ''}</td>
                <td>${formatDateTime(item.planned_Start)}</td>
                <td>${formatDateTime(item.createTime) || '-'}</td>
                <td>${formatDateTime(item.planned_Completion)}</td>
                <td>${formatDateTime(item.upDataTime) || '-'}</td>
                <td>${item.planned_Output || 0}</td>
                <td>${item.qualifiedNum || 0}</td>
                <td>${item.disqualificationNum || 0}</td>
                <td>${item.pass || '0%'}</td>
                <td>
                    <a href="/Home/OrderDetail/${item.id}" class="text-primary" onclick="viewOrderDetail(${item.id})">查看</a>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 获取状态徽章样式
    function getStatusBadgeClass(status) {
        switch (status) {
            case '待开始':
                return 'bg-secondary';
            case '进行中':
                return 'bg-primary';
            case '已完成':
                return 'bg-success';
            case '已暂停':
                return 'bg-warning';
            case '已取消':
                return 'bg-danger';
            default:
                return 'bg-secondary';
        }
    }

    // 格式化日期时间
    function formatDateTime(dateTimeString) {
        if (!dateTimeString) return '';
        try {
            const date = new Date(dateTimeString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (error) {
            return dateTimeString;
        }
    }

    // 渲染分页
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        if (totalPages <= 1) return;

        // 上一页
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="上一页">
                <span aria-hidden="true">&lt;</span>
            </a>
        `;
        pagination.appendChild(prevLi);

        // 当前页信息
        const infoLi = document.createElement('li');
        infoLi.className = 'page-item disabled';
        infoLi.innerHTML = `
            <span class="page-link">第 ${currentPage} 页 / 共 ${totalPages} 页</span>
        `;
        pagination.appendChild(infoLi);

        // 下一页
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="下一页">
                <span aria-hidden="true">&gt;</span>
            </a>
        `;
        pagination.appendChild(nextLi);
    }

    // 切换页面
    function changePage(page) {
        if (page < 1 || page > totalPages || page === currentPage) return;
        currentPage = page;
        loadWorkOrderData();
    }

    // 更新数据计数信息
    function updateDataCountInfo() {
        document.getElementById('dataCountInfo').textContent = `共 ${totalCount} 项数据`;
    }

    // 显示加载状态
    function showLoading() {
        document.getElementById('loadingSpinner').style.display = 'block';
        document.getElementById('workOrderTable').style.display = 'none';
        document.getElementById('noDataMessage').style.display = 'none';
        document.getElementById('paginationSection').style.display = 'none';
    }

    // 隐藏加载状态
    function hideLoading() {
        document.getElementById('loadingSpinner').style.display = 'none';
        document.getElementById('workOrderTable').style.display = 'table';
        document.getElementById('paginationSection').style.display = 'flex';
    }

    // 显示无数据
    function showNoData() {
        document.getElementById('noDataMessage').style.display = 'block';
        document.getElementById('workOrderTable').style.display = 'none';
        document.getElementById('paginationSection').style.display = 'none';
    }

    // 隐藏无数据
    function hideNoData() {
        document.getElementById('noDataMessage').style.display = 'none';
    }

    // 显示错误
    function showError(message) {
        alert('错误: ' + message);
    }

    // 应用查询条件
    function applyFilterConditions() {
        filterConditions = {
            orderNumber: document.getElementById('filterOrderNumber').value.trim(),
            orderName: document.getElementById('filterOrderName').value.trim(),
            articleName: document.getElementById('filterArticleName').value.trim(),
            status: document.getElementById('filterStatus').value,
            principal: document.getElementById('filterPrincipal').value.trim(),
            departmentName: document.getElementById('filterDepartment').value.trim()
        };

        // 移除空值
        Object.keys(filterConditions).forEach(key => {
            if (!filterConditions[key]) {
                delete filterConditions[key];
            }
        });

        currentPage = 1;
        loadWorkOrderData();
    }

    // 重置查询条件
    function resetFilterConditions() {
        document.getElementById('filterOrderNumber').value = '';
        document.getElementById('filterOrderName').value = '';
        document.getElementById('filterArticleName').value = '';
        document.getElementById('filterStatus').value = '';
        document.getElementById('filterPrincipal').value = '';
        document.getElementById('filterDepartment').value = '';
        
        filterConditions = {};
        currentPage = 1;
        loadWorkOrderData();
    }

    // 查看工单详情
    function viewOrderDetail(id) {
        // 跳转到详情页面，传递ID参数
        window.location.href = `/Home/OrderDetail/${id}`;
    }
</script>
